package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zsk
 * @create 2022-02-27-21:41
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    //依赖注入
    @Autowired
    private EmployeeMapper employeeMapper;

    //登录验证
    @Override
    public ResultInfo login(String username, String password) {

        //调用mapper层查询数据
        Employee employee = employeeMapper.findByUserName(username);
        if (employee == null){
            return ResultInfo.error("此用户不存在");
        }
        //兑前台传来的密码进行加密
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5,employee.getPassword())){//对比两个字符串是否相等
            //如果不等，则显示密码错误
            return ResultInfo.error("密码错误");
        }

        //判断挡墙用户状态
        if (employee.getStatus() != 1){
            return ResultInfo.error("当前用户属于禁用状态，请稍后再试！");
        }

        //都跳过表示登录成功，返回查询到的对象
        return ResultInfo.success(employee);
    }

    //查询用户列表
    @Override
    public List<Employee> findByName(String name) {

        //调用mapper层查询，返回结果
        return employeeMapper.findByName(name);
    }

    //添加用户信息
    @Override
    public void save(Employee employee) {
        //补齐参数
        //id:雪花算法生成唯一
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        //密码加密
        employee.setPassword(SecureUtil.md5("123456"));
        //设置状态
        employee.setStatus(1);

        //设置创建时间创建人与更新时间更新人
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());//todo 临时写死
//        employee.setCreateUser(1L);//todo 临时写死
//        employee.setUpdateUser(1L);

        //调用mapper层保存
        employeeMapper.save(employee);

    }

    //根据id查询用户信息
    @Override
    public Employee findById(Long id) {
        //调用mapper层查询
        return employeeMapper.findById(id);
    }

    //修改用户数据
    @Override
    public void update(Employee employee) {
        //确定修改的字段
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);//临时写死

        //调用mapper层修改
        employeeMapper.update(employee);
    }
}
